package com.example.pan.ui.drive

import androidx.lifecycle.ViewModel
import androidx.lifecycle.asLiveData
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.cachedIn
import com.example.pan.data.DriveDataSourceImpl
import com.example.pan.model.BAIDU_DRIVE
import com.example.pan.model.Drive
import com.example.pan.model.DriveDao
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class DriveViewModel @Inject constructor(
    private val driveDao: DriveDao,
    private val driveDataSourceImpl: DriveDataSourceImpl
) : ViewModel() {

    val drivePageSource = Pager(config = PagingConfig(10)) {
        driveDao.pagingSource()
    }.flow.cachedIn(viewModelScope)

    @ExperimentalCoroutinesApi
    fun loginDrive(type: Int, token: String) {
        viewModelScope.launch(Dispatchers.IO) {
            driveDataSourceImpl.getUserInfo(token)
                .collect {
                    driveDao.insertAll(
                        Drive(
                            title = it.netdisk_name,
                            type = BAIDU_DRIVE,
                            token = token
                        )
                    )
                }
        }
    }

}